/**
 * 图片blob转图片base64
 * @param blob
 */
export function blobToBase64(blob) {
  console.log(blob)
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = (e) => {
      resolve(e.target.result)
    }
    fileReader.readAsDataURL(blob)
    fileReader.onerror = () => {
      reject(new Error('blobToBase64 error'))
    }
  })
}

/**
 * 图片base64转blob
 * @param base64 base64图片
 */
export function base64ToBlob(base64) {
  let bstr = window.atob(base64);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: base64 })
}
/**
 * 根据图片url转为file文件对象
 * @param url
 * @param imageName
 * @returns {Promise<unknown>}
 */
export function getImageFileFromUrl(url, imageName) {
  return new Promise((resolve, reject) => {
      var blob = null;
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.setRequestHeader('Accept', 'image/png');
      xhr.responseType = "blob";
      // 加载时处理
      xhr.onload = () => {
        // 获取返回结果
          blob = xhr.response;
          let imgFile = new File([blob], imageName, { type: 'image/png' });
          // 返回结果
          resolve(imgFile);
      };
      xhr.onerror = (e) => {
          reject(e)
      };
      // 发送
      xhr.send();
  });
}
